import Hello from '@/pages/Hello'
import { Suspense } from 'react'
import KeepAlive from 'react-activation'
import { Navigate, RouteObject, useRoutes } from 'react-router'
import { metaRoutersProps } from './interface'

const metaRouters = require.context('./modules/', true, /\.tsx$/)
console.log(metaRouters)

// * 处理路由
export const routerArray = metaRouters.keys().reduce((modules: any, path) => {
	const module = metaRouters(path)
	console.log(path, module, module.default)
	modules = [...modules, ...module.default]
	return modules
}, [])

console.log(routerArray)

export const rootRouter: metaRoutersProps[] = [
	{
		path: '/',
		element: <Navigate to="/home" />,
	},
	{
		path: '/home',
		element: <Hello />,
	},
	...routerArray,
	{
		path: '*',
		element: <Navigate to="/404" />,
	},
]

const loading = <div style={{ display: 'flex', height: '100vh' }}>dwdw</div>

/** 懒加载处理 */
const syncRouter = (routes: Array<metaRoutersProps>): RouteObject[] => {
	const mRouteTable: RouteObject[] = []
	routes.forEach((item) => {
		mRouteTable.push({
			path: item.path,
			element: <Suspense fallback={loading}>{item.meta?.keepAlive ? <KeepAlive id={item.path}>{item.element}</KeepAlive> : item.element}</Suspense>,
			children: item.children && syncRouter(item.children),
		})
	})
	return mRouteTable
}

const Router = () => {
	const routes = useRoutes(syncRouter(rootRouter))
	return routes
}

export default Router
